<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    :show-close="false"
    :title="isAdd ? '新建人群' : '修改人群'"
    width="900"
  >
    <el-form
      ref="formRef"
      :model="crowdData"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="人群名称" prop="crowdName">
        <el-input
          v-model.trim="crowdData.crowdName"
          placeholder="请输入2-10个字符"
          maxlength="10"
          onblur="value=value.replace(/(^\s*)|(\s*$)/g, '')"
          show-word-limit
          style="width: 300px;"
        />
      </el-form-item>
      <el-form-item label="特征筛选" required prop="conditions">
        <CondTypeSelect
          v-for="(item, index) of crowdData.conditions"
          ref="condTypeSelectRef"
          :key="index"
          :form="item"
          :disabled-items="types"
          :show-delete="index !== 0"
          style="margin: 0 0 15px 0;"
          @changeType="changeType(item, index)"
          @delete="deleteOptions(item, index)"
        />
      </el-form-item>
      <el-form-item>
        <div
          v-if="crowdData.conditions.length < 11"
          style="
          display: flex;
          align-items: center;
          line-height: 40px;
          cursor: pointer;
          "
          @click="addCondition"
        >
          <el-icon size="20"><CirclePlusFilled /></el-icon>
          <span>添加筛选条件</span>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveClustering">保 存</el-button>
        <el-button @click="closeClustering">取 消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import CondTypeSelect from './formCondType.vue'
import {
  conditionOptions
} from './optionsMap.js'
import {
  getLabelData,
  addCrowd,
  getCrowdDetail,
  crowdUpdate,
} from '@/api/customer'

const visible = ref(false)
const isAdd = ref(false)
const shopCrowdId = ref('')
const crowdData = ref({
  conditions: [
    {
      calculation: null,
      ids: [],
      labelIds: [],
      number: null,
      type: 1,
      userIds: [],
    },
  ],
  crowdName: '',
  shopCrowdId: null,
})
const formRef = ref();
const condTypeSelectRef = ref();

const tagList = ref([]) // 标签列表
const types = ref([1])

const rules = {
  crowdName: [
    { required: true, message: '请输入人群名称', trigger: 'blur' },
    { min: 2, max: 10, message: '请输入2-10个字符', trigger: 'blur' },
  ],
}
const emits = defineEmits(['reset'])

onBeforeMount(() => {
  getTagList()
})

const show = (id) => {
  visible.value = true
  if (id) {
    isAdd.value = false
    shopCrowdId.value = id
    getDetail()
  } else {
    shopCrowdId.value = null
    isAdd.value = true
    crowdData.value = {
      conditions: [
        {
          calculation: null,
          ids: [],
          labelIds: [],
          number: null,
          type: 1,
          userIds: [],
        },
      ],
      crowdName: '',
      shopCrowdId: null,
    }
  }
}
defineExpose({ show })
// 获取编辑详情
function getDetail () {
  getCrowdDetail({ shopCrowdId: shopCrowdId.value }).then((res) => {
    if (res.code === '') {
      crowdData.value = res.data
      crowdData.value.conditions.forEach((item) => {
        if (item.labelIds.length > 0) {
          let ids = []
          ids = item.labelIds.map(Number)
          item.labelIds = ids
        }
      })
      types.value = []
      crowdData.value.conditions.forEach((i) => {
        types.value.push(i.type)
      })
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 添加筛选
function addCondition () {
  for (let i = 1; i <= conditionOptions.length; i++) {
    if (!types.value.includes(i)) {
      crowdData.value.conditions.push({
        calculation: i === 9 || i === 10 ? 1 : null,
        ids: [],
        labelIds: [],
        number: null,
        type: i,
        userIds: [],
      })
      types.value.push(i)
      break
    }
  }
}
// 删除当前筛选
function deleteOptions (item, index) {
  types.value.splice(index, 1)
  crowdData.value.conditions.splice(index, 1)
}
// 保存提交新客户
function saveClustering () {
  Promise.all(condTypeSelectRef.value.map(item => {
    return item.formValidate()
  })).then(res => {
    formRef.value.validate(valid => {
      if (valid && !res.includes(false)) {
        const fn = shopCrowdId.value ? crowdUpdate : addCrowd
        fn(crowdData.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('操作成功')
            visible.value = false
            emits('reset')
          } else {
            ElMessage.error(res.message)
          }
        }).catch(err => {
          console.log(err)
        })
      }
    })
  })
}
// 取消新增
function closeClustering () {
  formRef.value.resetFields();
  condTypeSelectRef.value.forEach(item => {
    item.resetFields();
  })
  visible.value = false
}
// 初始化标签数据
function getTagList () {
  getLabelData().then(res => {
    if (res.code === '') {
      tagList.value = res.data
    }
  }).catch(err => {
    console.log(err)
  })
}

// 更改当前选项
function changeType (item, index) {
  let crowds = crowdData.value.conditions
  types.value = []
  crowds.forEach((i) => {
    types.value.push(i.type)
  })
  if (item.type === 9 || item.type === 10) {
    crowdData.value.conditions[index].calculation = 1
  }
}
</script>
